package rdbmq

import (
	"encoding/json"
	"fmt"
	"path"
	"server/dao"
	"server/models"
	serviceDownload "server/service/download"
	serviceStorage "server/service/storage"
	"strconv"
	"strings"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
)

func RdbCon() {
	keys := []string{"list1", "excel_export"}
	fmt.Printf("注册消费者:%#v\n", keys)
	for {
		content, _ := dao.RdbBRPop(keys...)
		if content != nil {
			fmt.Printf("%#v\n", content[1])
			switch content[0] {
			case "list1":
				DealList1(content[1])
			case "excel_export":
				DealExcelExport(content[1])
			}
		}
	}
}

func DealList1(ct string) {
	fmt.Printf("deal list1 %#v\n", ct)
}

func DealExcelExport(ct string) error {
	fmt.Printf("DealExcelExport %#v\n", ct)
	type ctParse struct {
		Name   string `json:"name"`
		Phone  string `json:"phone"`
		UserID uint32 `json:"user_id"`
	}
	var ctJson ctParse
	json.Unmarshal([]byte(ct), &ctJson)
	fmt.Printf("Parse %#v\n", ctJson)
	// 查询条件
	whereStr := []string{"status >= 0"}
	if ctJson.Name != "" {
		whereStr = append(whereStr, " AND name LIKE '%"+ctJson.Name+"%'")
	}
	if ctJson.Phone != "" {
		whereStr = append(whereStr, " AND phone LIKE '%"+ctJson.Phone+"%'")
	}
	whereStrLong := strings.Join(whereStr, "")

	var list []*models.AdminUser
	errFind := dao.DB.Model(&models.AdminUser{}).Select([]string{"id", "name", "phone", "status", "created_time", "updated_time"}).Where(whereStrLong).Find(&list).Error
	if errFind != nil {
		return errFind
	}

	f := excelize.NewFile()
	// 创建一个工作表
	index := f.NewSheet("Sheet1")
	// 设置单元格的值
	errSetHeader := f.SetSheetRow("Sheet1", "A1", &[]interface{}{"ID", "姓名", "手机号", "新建时间"})
	if errSetHeader != nil {
		return errSetHeader
	}

	for index, val := range list {
		fmt.Println(index, val)
		errSetRow := f.SetSheetRow("Sheet1", "A"+strconv.Itoa(index+2), &[]interface{}{val.ID, val.Name, val.Phone, time.Unix(int64(val.CreatedTime), 0).Format("2006-01-02 15:04:05")})
		if errSetRow != nil {
			fmt.Println(errSetRow)
			break
		}
	}

	// 设置工作簿的默认工作表
	f.SetActiveSheet(index)
	// 根据指定路径保存文件
	fileName := ctJson.Name + "的资料.xlsx"
	dst := path.Join("./upload", fileName)
	if err := f.SaveAs(dst); err != nil {
		fmt.Println(err)
	}
	cosUrl, errRes := serviceStorage.CosPut(dst, fileName)
	fmt.Printf("res: %#v\n", cosUrl)
	if errRes != nil {
		return errRes
	}
	var doc models.AdminDownload
	doc.Name = fileName
	doc.UserID = ctJson.UserID
	doc.Url = cosUrl
	doc.Status = 2
	doc.CreatedTime = uint64(time.Now().Unix())
	doc.UpdatedTime = uint64(time.Now().Unix())
	_, errCreate := serviceDownload.Create(doc)
	if errCreate != nil {
		return errCreate
	}
	return nil
}
